import socket
import threading
import datetime

# 聊天室客户端部分
class ChatRoomClient:
    def __init__(self, host, port):
        self.host = host  # 服务器 IP 地址
        self.port = port  # 服务器监听的端口号
        self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 创建 TCP 套接字
        self.nickname = None  # 用户昵称
        self.chat_history = []  # 保存聊天记录

    def connect(self):
        self.client_socket.connect((self.host, self.port))  # 连接到服务器
        self.nickname = input('Enter your nickname: ')
        self.client_socket.send(self.nickname.encode())
        welcome_message = self.client_socket.recv(1024)
        print(welcome_message.decode())

    def send_message(self, message):
        try:
            self.client_socket.send(message.encode())  # 将消息发送给服务器
        except Exception as e:
            print(e)
            print('Failed to send the message.')

    def receive_message(self):
        while True:
            try:
                message = self.client_socket.recv(1024)
                if message:
                    print(message.decode().strip())
                    self.chat_history.append(message.decode().strip())  # 将收到的消息保存到本地聊天记录中
            except Exception as e:
                print(e)
                break

    def disconnect(self):
        self.client_socket.close()

        # 将聊天记录保存到文件
        now = datetime.datetime.now().strftime('%Y-%m-%d')
        filename = f'{now} {self.nickname}.txt'

        with open(filename, 'w') as f:
            f.write('\n'.join(self.chat_history))

    def start(self):
        try:
            receive_thread = threading.Thread(target=self.receive_message)
            receive_thread.start()

            while True:
                message = input()
                if message == 'quit':
                    self.disconnect()  # 客户端退出时保存聊天记录
                    break
                else:
                    self.send_message(message)

        except Exception as e:
            print(e)
            self.disconnect()
            
if __name__ == '__main__':
    # 启动客户端
    client = ChatRoomClient('192.168.162.193', 8888)
    client.connect()
    client.start()